import React, { Fragment } from 'react';
import { connect } from 'dva';
import { Table, Card, Form, Button, message, Icon } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import styles from '../../styles/Manage.less';
import AllotRes2User from '@/pages/System/permission-apply/components/AllotRes2User';

@Form.create()
@connect(({ resource, loading }) => ({
  resource,
  loading: loading.models.resource,
}))
class PermissionApply extends React.Component {
  state = {
    allotResVisible: false, // 分配资源弹框可视化
  };

  // 表格字段
  columns = [
    {
      title: '资源名称',
      dataIndex: 'name',
      render: (text, record) => (
        <Fragment>
          {record.icon ? <Icon type={record.icon} /> : ''}&nbsp;&nbsp;<span>{text}</span>
        </Fragment>
      ),
    },
    { title: '描述', dataIndex: 'comment' },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'resource/fetchDepartmentResTree',
    });

    dispatch({
      type: 'resource/fetch',
      payload: {
        userOnly: true,
      },
    });
  }

  // 修改资源
  handleAllotModalVisible = flag => {
    this.setState({
      allotResVisible: !!flag,
    });
  };

  // 资源分配更新
  handleAllotResUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'resource/applyUserRes', // 申请资源
      payload: fields,
      callback: () => {
        message.success('申请提交成功，等待管理员审核');
        this.handleAllotModalVisible();
      },
    });
  };

  render() {
    const {
      resource: { data },
      loading,
    } = this.props;
    const { allotResVisible } = this.state;
    return (
      <PageHeaderWrapper title="资源申请" content="申请本部门拥有的资源">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageOperator}>
              <span className={styles.querySubmitButtons}>
                <Button type="primary" onClick={() => this.handleAllotModalVisible(true)}>
                  资源申请
                </Button>
              </span>
            </div>
            <Table
              loading={loading}
              dataSource={data}
              columns={this.columns}
              rowKey={record => record.id}
            />
          </div>
        </Card>
        {allotResVisible && (
          <AllotRes2User
            handleModalVisible={this.handleAllotModalVisible}
            handleUpdate={this.handleAllotResUpdate}
            allotResVisible={allotResVisible}
          />
        )}
      </PageHeaderWrapper>
    );
  }
}

export default PermissionApply;
